﻿using System;
using System.Windows;
using System.Windows.Controls;
using Red.Controls.DataDriven;
using Red.Controls.ViewModels;
using Red.Core;

namespace Red.Controls.Shell
{
    /// <summary>
    ///     Finds templates basing on DataItem's data type
    /// </summary>
    public abstract class DataItemTemplateSelectorBase : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate( object item, DependencyObject container )
        {
            var c = container as FrameworkElement;
            var dataItem = item as DataItem;
            if ( dataItem != null )
            {
                Type controlType;
                if ( !string.IsNullOrWhiteSpace( dataItem.Type ) && InteropControlAttribute.ControlMap.TryGetValue( dataItem.Type, out controlType ) )
                {
                    return DataControlTemplateMapper.GetTemplateForControl( controlType );
                }
                else
                {
                    return GetDefaultTemplate( c );
                }
            }

            // fall-back to default mechanism
            return base.SelectTemplate( item, container );
        }

        protected abstract DataTemplate GetDefaultTemplate( FrameworkElement element );
    }

    public class TreeItemTemplateSelector : DataItemTemplateSelectorBase
    {
        private static DataTemplate _defaultTemplate;

        static TreeItemTemplateSelector()
        {
            _defaultTemplate = DataControlTemplateMapper.GetTemplateForControl( typeof( RedTreeItemView ) );
        }

        protected override DataTemplate GetDefaultTemplate( FrameworkElement element )
        {
            return _defaultTemplate;
        }
    }
}
